package com.masasdani.paypal.controller;

import com.masasdani.paypal.config.PaypalPaymentIntent;
import com.masasdani.paypal.config.PaypalPaymentMethod;
import com.masasdani.paypal.service.PayPalSubscriptionService;
import com.masasdani.paypal.service.PaypalService;
import com.masasdani.paypal.util.URLUtils;
import com.paypal.api.payments.*;
import com.paypal.base.rest.PayPalRESTException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;
import java.util.UUID;

/**
 * paypal支付控制类
 */
@Controller
@RequestMapping("/paypal/")
public class PaypalController {
	
	public static final String PAYPAL_SUCCESS_URL = "pay/success";
	public static final String PAYPAL_CANCEL_URL = "pay/cancel";
	public static final String PAYPAL_REFUND_URL = "refund/success";

	private Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private PaypalService paypalService;

	@Autowired
	private PayPalSubscriptionService payPalSubscriptionService;

	
	@RequestMapping(method = RequestMethod.GET)
	public String index(){
		return "index";
	}


	/**
	 * 创建支付
	 * @param request
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "pay")
	public String pay(HttpServletRequest request){
		String cancelUrl = URLUtils.getBaseURl(request) + "/paypal/" + PAYPAL_CANCEL_URL;
		String successUrl = URLUtils.getBaseURl(request) + "/paypal/" + PAYPAL_SUCCESS_URL;
		try {
			Random random = new Random();
			int randomNumber = random.nextInt(10);
			double total = 6;
			Payment payment = paypalService.createPayment(
					total,
					"USD", 
					PaypalPaymentMethod.paypal, 
					PaypalPaymentIntent.sale,
					"paypal description",
					cancelUrl, 
					successUrl);
			for(Links links : payment.getLinks()){
				if(links.getRel().equals("approval_url")){
					return "redirect:" + links.getHref();
				}
			}
		} catch (PayPalRESTException e) {
			log.error(e.getMessage());
		}
		return "redirect:/";
	}

	/**
	 * 支付结果失败
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = PAYPAL_CANCEL_URL)
	public String cancelPay(){
		return "cancel";
	}

	/**
	 * 支付结果成功
	 * @param paymentId
	 * @param payerId
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = PAYPAL_SUCCESS_URL)
	public String successPay(@RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId){
		try {
			Payment payment = paypalService.executePayment(paymentId, payerId);
			if(payment.getState().equals("approved")){
				// 订单号
				String saleId = payment.getTransactions().get(0).getRelatedResources().get(0).getSale().getId();
				String money = payment.getTransactions().get(0).getRelatedResources().get(0).getSale().getAmount().getTotal();
				//执行自己支付成功的业务方法
				log.info("PDT通知：交易成功回调");
				log.info("付款人账户："+payment.getPayer().getPayerInfo().getEmail());
				log.info("付款金额："+money);
				log.info("支付订单Id: {}",paymentId);
				log.info("支付订单状态state：" + payment.getState());
				log.info("交易订单Id: {}",saleId);
				log.info("交易订单状态state："+payment.getTransactions().get(0).getRelatedResources().get(0).getSale().getState());
				log.info("交易订单支付时间："+payment.getTransactions().get(0).getRelatedResources().get(0).getSale().getCreateTime());
				return "success";
			}
		} catch (PayPalRESTException e) {
			log.error(e.getMessage());
		}
		return "redirect:/";
	}

	/**
	 * 支付退款
	 * @param saleId
	 * @param amountToRefund
	 * @return
	 * @throws PayPalRESTException
	 */
	@RequestMapping(method = RequestMethod.GET, value = PAYPAL_REFUND_URL)
	public String refundPayment(@RequestParam("saleId") String saleId, @RequestParam("amountToRefund") double amountToRefund) throws PayPalRESTException {
		try {
			Refund refund = paypalService.refund(saleId, amountToRefund,"USD","");
			if (refund != null) {
				// 成功退款
				log.info("退款成功");
				//修改订单及用户状态
				return "success";
			} else {
				// 退款失败
				log.info("退款失败");
				return "error";
			}
		} catch (PayPalRESTException e) {
			log.error(e.getMessage());
		}
		return "redirect:/";
	}

}
